<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录: 16条</span>
        </template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import')"
            >excel导入</el-button
          >
          <el-button type="danger" size="small" @click="handleDownload"
            >excel导出</el-button
          >
          <el-button type="primary" size="small" @click="hAdd"
            >新增员工</el-button
          >
        </template>
      </PageTools>
      <el-card style="margin-top: 10px">
        <!-- 具体页面结构 -->
        <!-- 员工管理 -->
        <el-table border :data="list">
          <el-table-column label="序号" type="index" :index="orderIndex" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/' + scope.row.id)"
                >查看</el-button
              >
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <!-- 分页组件 -->
        <el-pagination
          :current-page="curPage"
          :page-sizes="[2, 3, 4, 5]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <!-- 表单弹框 -->
      <el-dialog
        title="新增员工"
        :visible.sync="isShowDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <empDialog v-if="isShowDialog" @success="hSuccess" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import empDialog from './empDialog.vue'
import employeesMenu from '@/constant/employees'
const map = employeesMenu.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value
  return acc
}, {})
export default {
  components: {
    empDialog
  },
  data() {
    return {
      list: [],
      // 当前页码
      curPage: 1,
      // 每页数量
      pageSize: 2,
      // total 总数量
      total: 0,
      // 控制弹框显示隐藏
      isShowDialog: false,
      // 表头
      tHeader: []
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    format(id) {
      return map[id] || '未知'
    },
    orderIndex(index) {
      return (this.curPage - 1) * this.pageSize + index + 1
    },
    async getEmployeeList() {
      const res = await getEmployeeList(this.curPage, this.pageSize)
      console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 页码改变请求数据
    handleCurrentChange(value) {
      this.curPage = value
      this.getEmployeeList()
    },
    // 改变每页条数请求数据
    handleSizeChange(value) {
      this.pageSize = value
      this.getEmployeeList()
    },
    async doDel(id) {
      await delEmployee(id)
      // 如果是删除的最后一页的最后一条数据 页面就会显示不正常
      if (this.list.length === 1) {
        this.curPage--
        if (this.curPage <= 0) {
          this.curPage = 1
        }
      }
      this.getEmployeeList()
    },
    // 点击新增
    hAdd() {
      // 显示弹框
      this.isShowDialog = true
    },
    // 点击删除
    hDel(id) {
      // 弹层询问，是否退出
      this.$confirm('你确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.doDel(id)
          this.$message.success('删除成功')
          this.getEmployeeList()
        })
        .catch(() => {
          // 用户取消退出
        })
    },
    hSuccess() {
      this.isShowDialog = false
      // 添加成功,进入最后一页看数据
      this.total++
      // 最后一页
      this.curPage = Math.ceil(this.total / this.pageSize)
      this.getEmployeeList()
    },
    async handleDownload() {
      this.downloadLoading = true
      const res = await getEmployeeList(this.curPage, this.total)
      import('@/vendor/Export2Excel').then(excel => {
        const list = res.data.rows
        const data = this.formatJson(list)
        const tHeader = this.tHeader
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '前端87', // 定义文件名
          autoWidth: this.autoWidth, // 定义表格宽度 默认为true
          bookType: this.bookType // 定义文件格式 默认是xlsx
        })
        this.downloadLoading = false
      })
    },
    formatJson(list) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      this.tHeader = Object.values(map)
      // 目的:得到一个二维数组
      return list.map(item => {
        return Object.keys(map).map(key => {
          return item[key]
        })
      })
    }
  }
}
</script>
